#include "BHomeView.h"
#include "ui_BHomeView.h"

BHomeView::BHomeView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::BHomeView)
{
    ui->setupUi(this);

    initStackWidget();

//    addItemAndMonitor(data, netData);
}

BHomeView::~BHomeView()
{
    for (int i = 0; i < m_itemVector.size(); i++) {
        delete m_itemVector[i];
    }
    for (int i = 0; i < m_monitorVector.size(); i++) {
        delete m_monitorVector[i];
    }
    delete m_robotMap;
    delete ui;
}

void BHomeView::addItemAndMonitor(const RobotBaseData &baseData, const RobotNetData &netData)
{
    RobotItem* item = new RobotItem(QRectF(-250, -250, 500, 500),
                                    baseData);
    RobotStateMonitor* monitor = new RobotStateMonitor(baseData,
                                                       netData, this);
    //添加item和monitor
    m_itemVector.push_back(item);
    m_monitorVector.push_back(monitor);
    //建立item和monitor的连接关系
    connect(monitor, &RobotStateMonitor::sendData, item, &RobotItem::setRobotData);
    connect(item, &RobotItem::dataChanged, monitor, &RobotStateMonitor::setData);
    //加入到ui
    m_robotMap->addRobotItem(item);
    ui->scrollLayout->addWidget(monitor);

}

void BHomeView::initStackWidget()
{
    //1.初始化包含组件
    m_robotMap = new RobotMap(ui->stackedWidget);

    //2.初始化stackedWidget
    ui->stackedWidget->insertWidget(0, m_robotMap);

    //3.设置connct

    //4.设置初始状态
    ui->stackedWidget->setCurrentIndex(0);
}

void BHomeView::on_pushButton_clicked()
{
    RobotItemDialog* itemDialog = new RobotItemDialog(this);
    int ret = itemDialog->exec();  ///模态显示
    if (ret == QDialog::Accepted) {
//        std::cout << itemDialog->getBaseData() << std::endl;
        addItemAndMonitor(itemDialog->getBaseData(), itemDialog->getNetData());
    }
    else if (ret == QDialog::Rejected) {
        qDebug() << "Rejected";
    }
    //warning:经测试，必须主动进行Dialog的析构
    itemDialog->~RobotItemDialog();
}
